<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/9 0009
 * Time: 17:11
 */

namespace Cohuna\Models;

use Phalcon\Di;

/**
 * 用户信息
 * @package Cohuna\Models
 */
class CohunaMember extends ModelBase
{
    public $member_id;
    public $account;
    public $password;
    public $realname;
    public $email;
    public $phone;
    public $telephone;
    public $avatar_url;
    public $role_id;
    public $status;
    public $source;
    public $create_time;
    public $create_id;
    public $update_time;
    public $last_login_time;
    public $permission_list;

    public function initialize()
    {
        parent::initialize();
        $this->skipAttributes(array('permission_list'));
    }

    public function getSource()
    {
        return Di::getDefault()->getShared('config')->database->default->prefix . 'member';
    }
    public function beforeUpdate()
    {
        $this->update_time = date('Y-m-d H:i:s');
    }
    public function beforeCreate()
    {
        $this->create_time = date('Y-m-d H:i:s');
    }

    public function afterFetch()
    {
        if($this->role_id > 0){
            $role = CohunaPermissionRole::findFirstByRoleId($this->role_id);
            if(empty($role) === false){
                $this->permission_list = CohunaPermissionResource::find(array(
                   'resource_id IN ({resource_id:array})',
                    'bind' => array('resource_id'=>$role->resource_list)
                ));
            }
        }
    }

    public function isPermission($controller,$action)
    {
        if($this->role_id == 0){
            return true;
        }
        if(empty($this->permission_list) === false){
            foreach ($this->permission_list as $item){
                if($item->controller_name == $controller && $item->acton_name){
                    return true;
                }
            }
        }
        return false;
    }
}